package com.zretc.controller;

import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.zretc.api.SendCaptcha;
import com.zretc.entity.Account;
import com.zretc.service.AccountService;
import com.zretc.service.impl.AccountServiceImpl;
import com.zretc.util.Md5;

/**
 * Servlet implementation class AccountServlet
 */
@WebServlet("/AccountServlet")
@MultipartConfig
public class AccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private AccountService accountService = new AccountServiceImpl();
	private Md5 md5 = new Md5();
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AccountServlet() {
		super();
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		String op = request.getParameter("op");
		if ("login".equals(op)) {
				doLogin(request, response);
		} else if ("existsOfAccountTel".equals(op)) {
			doExistsOfAccountTel(request, response);
		} else if ("sendCaptcha".equals(op)) {
			doSendCaptcha(request, response);
		} else if ("register".equals(op)) {
			doRegister(request, response);
		}
	}

	private void doRegister(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		// 业务逻辑层
		String accountTel = request.getParameter("registerAccount");
		String accountPwd = request.getParameter("registerPwd");
		//Md5加密
		try {
			accountPwd = md5.EncoderByMd5(accountPwd);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	
		Account loginAccount = null;
		Part part = request.getPart("accountPicture");
		if (part==null) {
			loginAccount = new Account(null, accountTel, accountPwd, 0, null);
			accountService.register(loginAccount);
			// 重定向到前台首页
			response.sendRedirect("front/register_login.jsp？registerSuccess=success");
		} else {
			String allowImgType = "image/jpg,image/jpeg,image/png";
			List<String> allowImgTypeList = Arrays.asList(allowImgType.split(","));
			String contentType = part.getContentType();

			if (allowImgTypeList.contains(contentType) == false) {
				response.sendRedirect("front/register_login.jsp?fileuploaderror=fileuploaderror");
			} else {
				String header = part.getHeader("content-disposition");
				String realName = header.substring(header.indexOf("filename=") + 10, header.length() - 1);
				// 获取文件后缀名
				String fileSuffix = realName.substring(realName.lastIndexOf("."));
				// 时间戳+随机数
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");
				String time = ofPattern.format(now);
				int random = (int) (Math.random() * 10000 + 1);
				StringBuffer stringBuffer = new StringBuffer();
				stringBuffer.append(time).append(random).append(fileSuffix);
				// 文件统一放到一个目录中
				File file = new File("E:/files/images");
				if (!file.exists()) {
					// 创建目录
					file.mkdirs();
				}
				String filePath = file.getPath() + file.separator + stringBuffer;
				part.write(filePath);
				
				loginAccount = new Account(null, accountTel, accountPwd, 0, stringBuffer.toString());

				accountService.register(loginAccount);
				// 重定向到前台首页
				response.sendRedirect("front/register_login.jsp？registerSuccess=success");
			}
		}
	}

	private void doSendCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String phoneNum = request.getParameter("phoneNum");
		SendCaptcha sendCaptcha = new SendCaptcha();
		String random = sendCaptcha.getCaptcha(phoneNum);
		HttpSession session = request.getSession();
		session.setAttribute("random", random);
		response.getWriter().write(random);
	}

	private void doExistsOfAccountTel(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String accountTel = request.getParameter("accountTel");
		boolean existsOfAccount = accountService.existsOfAccountTel(accountTel);
		if (existsOfAccount == false) {

			response.getWriter().write("false");
		} else {
			response.getWriter().write("true");
		}
	}

	private void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String accountTel = request.getParameter("accountTel");
		String accountPwd = request.getParameter("accountPwd");
		//Md5加密
		try {
			accountPwd = md5.EncoderByMd5(accountPwd);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		
		Account loginAccount = accountService.login(accountTel, accountPwd);
		if (loginAccount == null) {
			response.sendRedirect("front/register_login.jsp?loginError=loginError");
		} else {
			HttpSession session = request.getSession();
			session.setAttribute("loginAccount", loginAccount);
			response.sendRedirect("front/index.jsp");
		}

	}

}
